package com.boyinet.imesh2json.viewmodel

import com.boyinet.imesh2json.bean.DataMap
import com.boyinet.imesh2json.model.DataMapModel
import com.boyinet.imesh2json.repo.DataMapRepository
import javafx.beans.property.SimpleStringProperty
import javafx.beans.property.StringProperty
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
class DataMapsViewModel {

    val log: Logger = LoggerFactory.getLogger(DataMapsViewModel::class.java)

    @Autowired
    lateinit var dataMapRepository: DataMapRepository

    var dataMaps: ObservableList<DataMap> = FXCollections.observableArrayList()

    var current: DataMapModel = DataMapModel()

    var index: Int = 0

    var currentTemplateId: Long? = null

    var update = false

    fun show(id: Long) {
        currentTemplateId = id
        val toList = dataMapRepository.findDataMapsByTemplateIdEquals(id)
        if (toList.isEmpty()) {
            dataMaps.clear()
        } else {
            dataMaps.setAll(toList)
        }
    }

    fun update() {
        dataMaps[index] = current.export()
    }

    fun save() {
        dataMaps.add(current.export())
    }

    fun delete(selectedItem: DataMap?) {
        selectedItem?.let {
            dataMaps.remove(selectedItem)
        }
    }

    fun saveAll() {
        dataMapRepository.saveAll(dataMaps)
    }

    fun deleteAll(id: Long) {
        val dataMaps = dataMapRepository.findDataMapsByTemplateIdEquals(id)
        log.info("[DataMapsViewModel DeleteAll] templateId : $id, dataMapList info : $dataMaps")
        dataMapRepository.deleteAll(dataMaps)
    }
}